const DB_NAME = 'DB_MANAGE'
const DB_VERSION = 1
let dbPromise: Promise<IDBDatabase>

export const openDB = async (tableName: string) => {
  if (!dbPromise) {
    dbPromise = new Promise((resolve, reject) => {
      const openRequest = indexedDB.open(DB_NAME, DB_VERSION)
      openRequest.onerror = () => {
        reject(openRequest.error)
      }
      openRequest.onsuccess = () => {
        resolve(openRequest.result)
      }
      openRequest.onupgradeneeded = () => {
        const db = openRequest.result
        if (db.objectStoreNames.contains(tableName)) {
          db.deleteObjectStore(tableName)
        }
        db.createObjectStore(tableName, {
          keyPath: 'id',
          autoIncrement: true,
        })
      }
    })
  }
  return dbPromise
}

export const createData = async <T>(data: T, tableName: string): Promise<T> => {
  const db = await openDB(tableName)
  const tx = db.transaction(tableName, 'readwrite')
  const store = tx.objectStore(tableName)
  const request = store.add(data)
  return await new Promise((resolve, reject) => {
    request.onsuccess = async () => {
      console.log('添加成功', request.result)
      const data = await fetchOne(request.result as number, tableName)
      resolve(data as T)
    }
    request.onerror = () => {
      reject(request.error)
    }
  })
}

// 读取数据
export const readData = async <T>(tableName: string): Promise<T[]> => {
  const db = await openDB(tableName)
  const tx = db.transaction(tableName, 'readonly')
  const store = tx.objectStore(tableName)
  const request = store.getAll()
  return await new Promise((resolve, reject) => {
    request.onsuccess = () => {
      resolve(request.result as T[])
    }
    request.onerror = () => {
      reject(request.error)
    }
  })
}

// 读取指定数据
export const fetchOne = async <T>(id: number, tableName: string): Promise<T> => {
  const db = await openDB(tableName)
  const tx = db.transaction(tableName, 'readonly')
  const store = tx.objectStore(tableName)
  const request = store.get(id)
  return await new Promise((resolve, reject) => {
    request.onsuccess = () => {
      resolve(request.result as T)
    }
    request.onerror = () => {
      reject(request.error)
    }
  })
}

// 更新数据
export const updateData = async <T>(data: T, tableName: string): Promise<T> => {
  const db = await openDB(tableName)
  const tx = db.transaction(tableName, 'readwrite')
  const store = tx.objectStore(tableName)
  const request = store.put(data)
  return await new Promise((resolve, reject) => {
    request.onsuccess = () => {
      resolve(request.result as T)
    }
    request.onerror = () => {
      reject(request.error)
    }
  })
}

// 删除数据
export const deleteData = async <T>(key: number, tableName: string): Promise<T> => {
  // 检查数据是否存在
  const existingData = await fetchOne(key, tableName)
  if (!existingData) {
    throw new Error('数据不存在')
  }

  const db = await openDB(tableName)
  const tx = db.transaction(tableName, 'readwrite')
  const store = tx.objectStore(tableName)
  const request = store.delete(key)
  return await new Promise((resolve, reject) => {
    request.onsuccess = () => {
      resolve(request.result as T)
    }
    request.onerror = () => {
      reject(request.error)
    }
  })
}
